import cv2
import numpy as np


def image_resize(img, input_size, gt_boxes):
    gt_boxes = np.array(gt_boxes)
    img_h, img_w = img.shape[0], img.shape[1]
    input_h, input_w = input_size[0], input_size[1]
    ratio = min(input_h / img_h, input_w / img_w)

    resize_h, resize_w = int(ratio * img_h), int(ratio * img_w)
    resized_img = cv2.resize(img, (resize_w, resize_h))

    top_bottom_fill_pixes = int((input_h - resize_h) / 2)
    left_right_fill_pixes = int((input_w - resize_w) / 2)

    # 上下左右填充固定的值
    fill_img = cv2.copyMakeBorder(resized_img, top_bottom_fill_pixes, top_bottom_fill_pixes,
                                  left_right_fill_pixes, left_right_fill_pixes,
                                  cv2.BORDER_CONSTANT, value=[127.5, 127.5, 127.5])
    # 如果出现不能整除的情况, 那么就会出现fill_img的大小，并不是input_size的大小， 所以这里需要进一步的resize
    img_output = cv2.resize(fill_img, (input_w, input_h))

    gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * ratio + left_right_fill_pixes
    gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * ratio + top_bottom_fill_pixes
    return img_output, gt_boxes


def image_preporcess(img, input_size, gt_boxes):
    gt_boxes = np.array(gt_boxes)
    img_h, img_w = img.shape[0], img.shape[1]
    input_h, input_w = input_size[0], input_size[1]
    ratio = min(input_h / img_h, input_w / img_w)

    resize_h, resize_w = int(ratio * img_h), int(ratio * img_w)
    resized_img = cv2.resize(img, (resize_w, resize_h))

    top_bottom_fill_pixes = int((input_h - resize_h) / 2)
    left_right_fill_pixes = int((input_w - resize_w) / 2)

    # 上下左右填充固定的值
    fill_img = cv2.copyMakeBorder(resized_img, top_bottom_fill_pixes, top_bottom_fill_pixes,
                                  left_right_fill_pixes, left_right_fill_pixes,
                                  cv2.BORDER_CONSTANT, value=[127.5, 127.5, 127.5])

    # 如果出现不能整除的情况, 那么就会出现fill_img的大小，并不是input_size的大小， 所以这里需要进一步的resize
    img_output = cv2.resize(fill_img, (input_w, input_h))
    # img_output /= 255.0
    img_output = img_output / np.array([255.0, 255.0, 255.0])

    gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * ratio + top_bottom_fill_pixes
    gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * ratio + left_right_fill_pixes

    return img_output, gt_boxes
